var id = null;

$(document).ready(function () {
    // reading account list from database
    if (document.getElementById('account_list') != null) {
        $("#account_list").ready(function () {
            $("#account_list").css("display", "block");
            $("#account_list").html("<span style='color: green'>loading .... </span> ");
            readAccount('');
        });
    }

    // reading news list from database
    if (document.getElementById('album_list') != null) {
        $("#album_list").ready(function () {
            $("#album_list").css("display", "block");
            $("#album_list").html("<span style='color: green'>loading .... </span> ");
            readAlbums("");
        });
    }
});

// ACCOUNT Management
function readAccount(datastr) {
    $.ajax({
        type: "POST",
        url: "getListAccount.do",
        dataType: "html",
        data: datastr,
        cache: false,
        success: function (html) {
            $("#account_list").html(html);
        }
    });

    return false;
}

function showEditFormAccount(index, username, password, email) {
    $("#id_acc").val(index);
    $("#username").val(urldecode(username));
    $("#password").val(password);
    $("#email").val(email);
    $("#username").focus();
    return false;
}

function deleteAccount() {
    if (id != null) {
        var datastr = "id_acc=" + id;

        $.ajax({
            type: "POST",
            url: "deleteAccount.do",
            data: datastr,
            dataType: "json",
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },
            success: function (html) {
            	if (html == null || html.status == null || html.status.trim() == '') {
            		window.location.href = "404.do";
            	} else if (html != null && html.status.trim() == 'fail') {
                    alert("Error occurs!");
                } else {
                    if ($("#id_acc").val() == id) {
                        $("#id_acc").val(null);
                    }
                    readAccount("");
                }
            },
            error: function(response) {
            	window.location.href = "404.do";
            }
        });

        $("#dialog").dialog("close");

        return false;
    }

    return false;
}

function createAccount() {
    var id_acc = $("#id_acc").val();
    var username = encodeURIComponent($("#username").val());
    var password = encodeURIComponent($("#password").val());
    var email = $("#email").val();

    if (id_acc.trim() == '') {
        id_acc = null;
    }

    if (username.trim() != '' && password.trim() != '' && validate(email)) {
        var datastr = 'id_acc=' + id_acc + '&username=' + username + '&password=' + password + '&email=' + email;
        $.ajax({
            type: "POST",
            url: "createAccount.do",
            data: datastr,
            dataType: 'json',
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },
            success: function (html) {
                readAccount("");
                $("#message").css("display", "block");
                $("#message").fadeIn("slow");
                $("#message").html(html.message.trim());
                $("#message").fadeOut(2000);
                $("#accountForm")[0].reset();

                $("#id_acc").val(null);
                $("#username").focus();
            }
        });
    }

    return false;
}

function resetFormAcc() {
    $("#username").focus();
    $("#id_acc").val(null);
}
///END ACOUNT


function showConfirmDialog(index) {
    id = index;
    $("#dialog").dialog();
    return false;
}
function closeDialog() {
    $("#dialog").dialog("close");
    return false;
}

//
function validate(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

// decode
function urldecode(url) {
    return decodeURIComponent(url.replace(/\+/g, ' '));
}

function OpenDialog() {
    var Return = window.showModalDialog("dialogImage.php", "", "dialogWidth:700px;dialogHeight:600px;");
    if (Return != null) {
        document.getElementById("image").value = Return.link;
    }
}

/// Albums MANAGEMENT
function readAlbums(datastr) {
    $.ajax({
        type: "POST",
        url: "getListAlbums.php",
        data: datastr,
        cache: false,
        success: function (html) {
            $("#album_list").html(html);
        }
    });

    return false;
}

function showEditFormAlbum(index, title, url_image, folder, description) {
    $("#id_album").val(index);
    $("#name").val(urldecode(title));
    $("#folder_url").val(folder);
    CKEDITOR.instances['description'].setData(urldecode(description));
    $("#image_url").val(url_image);
    $("#sample_image").html('<img src="' + url_image + '">');
    $("#name").focus();

    return false;
}

function deleteAlbum() {
    if (id != null) {
        var datastr = "id_album=" + id;

        $.ajax({
            type: "POST",
            url: "deleteAlbum.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },

            success: function (html) {
                readAlbums("");
                if ($("#id_album").val() == id) {
                    $("#id_album").val('');
                }
            }
        });

        $("#dialog").dialog("close");

        return false;
    }

    return false;
}

function createAlbum() {
    var id_album = $("#id_album").val();
    var name = encodeURIComponent($("#name").val());
    var album_url = ($("#folder_url").val());
    var description = encodeURIComponent(CKEDITOR.instances['description'].getData());
    var image_url = ($("#image_url").val());


    if (id_album.trim() == '') {
        id_album = null;
    }

    if (name.trim() != '') {
        var datastr = 'id_album=' + id_album + '&name=' + name + '&album_url=' + album_url + '&image_url=' + image_url + '&description=' + description;
        $.ajax({
            type: "POST",
            url: "createAlbum.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },

            success: function (html) {
                readAlbums("");
                $("#message").css("display", "block");
                $("#message").fadeIn("slow");
                $("#message").html(html);
                $("#message").fadeOut(2000);
                $("#albumForm")[0].reset();

                $("#id_album").val('');
                CKEDITOR.instances['description'].setData('');
                $("#image_url").val('../images/default.jpg');
                $("#folder_url").val('../FileUpload/');
                $("#sample_image").html('<img src="../images/default.jpg">');
            }
        });
    }

    return false;
}

function resetFormAlbum() {
    $("#name").focus();
    $("#id_album").val('');
    CKEDITOR.instances['description'].setData('');
    $("#sample_image").html('<img src="../images/default.jpg">');
}
// END Albums

function browserFolder() {
    var url_image = window.showModalDialog("dialogBrowserFolder.php", "", "dialogWidth:700px;dialogHeight:600px;");
    if (url_image != null) {
        $("#folder_url").val(url_image.link);
    }
}

function browserImage() {
    var url_image = window.showModalDialog("dialogImage.php", "", "dialogWidth:700px;dialogHeight:600px;");
    if (url_image != null) {
        $("#image_url").val(url_image.link);
        $("#sample_image").html('<img src="' + url_image.link + '">');
    }
}